const config = require('./../../config')
const access = require('./access.js')
const log4js = require('log4js')

//定义日志级别
const methods = ["trace", "debug", "info", "warn", "error", "fatal", "mark"]

const { env, appLogLevel, dir } = config.baseInfo

module.exports = () => {
  const contextLogger = {}
  const appenders = {}

  appenders.cheese = {
    type: 'dateFile',
    filename: `${dir}/shop`,
    pattern: '-yyyy-MM-dd.log',
    alwaysIncludePattern: true
  }

  // 环境变量为dev local development 认为是开发环境
  if (env === "dev" || env === "local" || env === "development") {
    appenders.out = {
      type: "console"
    }
  }

  let logConfig = {
    appenders,
    categories: {
      default: {
        appenders: Object.keys(appenders),
        level: appLogLevel
      }
    }
  }
  return async (ctx, next) => {
    const start = +Date.now()
    log4js.configure(logConfig)
    const logger = log4js.getLogger('cheese');
    methods.forEach((method, i) => {
      contextLogger[method] = (message) => {
        logger[method](access(ctx, message, {}))
      }
    })
    ctx.log = contextLogger
    await next()
    const end = +Date.now()
    const responseTime = end - start
    logger.info(access(ctx, `响应时间为${responseTime/1000}s`, {}))
  }
}